"""
@author: 江同学呀
@file: core.py
@date: 2023/8/22 19:45
@desc:
"""
import warnings
from collections import defaultdict
from typing import Generator, List, Dict, Optional

from elasticsearch import Elasticsearch, ElasticsearchWarning

from espc.err import ESPCInitError


# 忽略ElasticsearchWarning
warnings.filterwarnings('ignore', category=ElasticsearchWarning)


class Core:
    _instance = None

    def __init__(self):
        self._es: Optional[Elasticsearch] = None
        return

    def __new__(cls, *args, **kwargs):
        if not isinstance(cls._instance, cls):
            cls._instance = super().__new__(cls)
        return cls._instance

    def __del__(self):
        try:
            self._es.close()
        except Exception:
            pass
        return

    @property
    def es(self) -> Elasticsearch:
        if self._es is None:
            raise ESPCInitError("ES未初始化")
        return self._es

    def init_es(self, *args, **kwargs):
        """
        初始化ES
        :param args:
        :param kwargs:
        """
        self._es: Elasticsearch = Elasticsearch(*args, **kwargs)
        return

    @staticmethod
    def _ref_field_name(model):
        """
        映射字段名字
        :param model: 索引模型
        :return:
        """
        from espc.orm.model.mapping.field.base_field.base_field import _BaseField

        generator: Generator = (
            model._get_custom_attrs() if not isinstance(model, type) else model._get_custom_attrs(model)
        )
        for field_name in (attr_name for attr_name in generator if not attr_name.startswith("_")):
            field = getattr(model, field_name)  # _BaseField
            if not isinstance(field, _BaseField):
                continue
            field._init_field_name(field_name=field_name)
            model._fields.append(field_name)
        return


core: Core = Core()

